package com.j1903.contorller;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.j1903.annotation.PassJwt;
import com.j1903.bean.Goods;
import com.j1903.bean.Users;
import com.j1903.service.GoodsService;
import com.j1903.service.IUsersService;
import com.j1903.service.UsersService;
import com.j1903.util.JsonResult;
import com.j1903.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Slf4j
@CrossOrigin
public class UsersController {
    @Resource
    private UsersService usersService;
    @RequestMapping("/front/reg")
    @PassJwt
    public JsonResult reg(String email,
                          String code,
                          HttpServletRequest request){
//        Map<String,Object> p=
//                (Map<String, Object>request.getAttribute("tokenParam"));
        String tokenParam=
                (String) request.getAttribute("tokenParam");
        if(!StringUtils.isEmpty(tokenParam)){
            ObjectMapper om=new ObjectMapper();
            try {
                Map<String,Object> param=
                        om.readValue(tokenParam,Map.class);
                String chkCode=param.get("code").toString();
                if(chkCode.equals(code)){
                    return new JsonResult(200, "验证通过", chkCode+"="+code);
                }
                return new JsonResult(500, "验证码错误", null);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return new JsonResult(500, "数据解析失败", null);
        }
        else{
            return new JsonResult(500, "未获取验证码", null);
        }

    }
    @RequestMapping("/front/login")
    @PassJwt
    public JsonResult login(
            @RequestBody Map<String,String> param){
        String userName=param.get("userName");
        String userPwd=param.get("userPwd");
        System.out.println(userName);
        List<Users> list=
                usersService.lists(new Users(userName, userPwd));
        if(list!=null&&list.size()==1){
            return new JsonResult(200, "登录成功",
                    JwtUtil.createToken(list.get(0).getId().toString(),
                            24*60,new HashMap<String,Object>(){{put("userName", userName);}}));
            //JwtUtil.createToken(list.get(0).getId().toString(),userName));

        }else{
            return new JsonResult(500, "账号或密码错误",null);
        }

    }

}
